# 功能模块：设备级，主页面入口
# 作者：dl
# 描述：设备级业务逻辑入口

import os
import vtk
from trame.app import asynchronous
import datetime
import asyncio
from gltf import GLTFLoader, GLTFRenderEngine

from visualizationCom.tools.color import hex_to_rgba


class deviceScene:
    # 构造函数
    def __init__(self, parent, webState, webCtrl):

        self.parent = parent
        self.webState = webState
        self.webCtrl = webCtrl

        self.hasLoadScene = False  # 用于判断是否存在缓存
        self.engine = GLTFRenderEngine()
        self.renderer = self.engine.GetDefaultRenderer()
        self.camera = self.engine.GetCamera()

        bg_color = hex_to_rgba('#132c4a')
        self.renderer.SetBackground(bg_color[0], bg_color[1], bg_color[2])

        self.materialColorList = []  # 记录模型各个零部件材质原来的颜色

        # 定义相机初始化位置，用于重置
        self.initial_position = 0
        self.initial_focal_point = 0
        self.initial_view_up = 0

        self.light = vtk.vtkLight()

        self.animationLastDateTime = None  # 动画需要用到的时间
        self.animationFlag = False

    def enterScene(self):

        self.parent.mouseInteractorEvent.outline.Clear()
        self.parent.mouseInteractorEvent.lastPick = None

        with self.webState:
            self.webState.sceneKey = 'device'

        self.parent.currentRenderer = self.renderer

        # 暂时写死模型
        if self.hasLoadScene == False:
            camera = self.renderer.GetActiveCamera()
            self.initial_position = camera.GetPosition()
            self.initial_focal_point = camera.GetFocalPoint()
            self.initial_view_up = camera.GetViewUp()

            CURRENT_DIRECTORY = os.path.dirname(
                os.path.dirname(os.path.dirname(__file__)))

            modePath = "model/device/product_line.glb"

            # 结合 CURRENT_DIRECTORY 和 modePath 形成新的地址
            new_directory = os.path.join(CURRENT_DIRECTORY, modePath)
            self.load_file(new_directory)

        self.hasLoadScene = True

        self.parent.renderWindow.AddRenderer(self.renderer)

        # 重置交互器
        self.engine.SetRenderWindow(self.parent.renderWindow)
        self.parent.mouseInteractorEvent.SetDefaultRenderer(self.renderer)
        self.parent.mouseInteractorEvent.SetOutlineRenderer(
            self.engine.GetOutlineRenderer())

        self.restCamera()
        self.parent.renderWindow.Render()
        self.webCtrl.view_update()

        self.webCtrl.sendMsgToParent({"eventScene":"device","eventName":"enterScene","value":"complete"})

    def leaveScene(self):
        self.parent.renderWindow.RemoveRenderer(self.renderer)
        
    def load_file(self, file_name):
        self.renderer.RemoveAllViewProps()

        self.reader = GLTFLoader()
        self.reader.Load(file_name)
        self.scene = self.reader.GetScene()
        self.renderer.AddScene(self.scene)

        if len(self.reader.animations):
            self.animationFlag = True
        else:
            self.animationFlag = False

    def restCamera(self):
        # 获取当前相机
        camera = self.renderer.GetActiveCamera()

        # 重置相机的位置和方向为初始状态
        camera.SetPosition(self.initial_position)
        camera.SetFocalPoint(self.initial_focal_point)
        camera.SetViewUp(self.initial_view_up)
        self.renderer.ResetCamera()

    def changeEvn(self,bgIndex):
        if bgIndex == 1:
            # CURRENT_DIRECTORY = os.path.dirname(
            #     os.path.dirname(os.path.dirname(__file__)))

            # modePath = "3dENV/spaichingen_hill_1k.hdr"

            # # 结合 CURRENT_DIRECTORY 和 modePath 形成新的地址
            # new_directory = os.path.join(CURRENT_DIRECTORY, modePath)
            # self.renderer.SetEnvmap(new_directory)
            bg_color = hex_to_rgba('#041A21')
            self.renderer.SetBackground(bg_color[0], bg_color[1], bg_color[2])
        else:
            bg_color = hex_to_rgba('#132c4a')
            self.renderer.SetBackground(bg_color[0], bg_color[1], bg_color[2])
        self.parent.renderWindow.Render()
        self.webCtrl.view_update()
        self.webCtrl.view_update()
        
    @asynchronous.task
    async def async_animation(self): 
        # check animation
        if self.animationFlag == False:   
            self.scene.SetActiveAnimation(-1)
            print("stop animation") 
            return    
        
        print("start animation")    
        self.scene.SetActiveAnimation(0)
        start = datetime.datetime.now() 
        lastUpdate = start        
        while self.animationFlag: 
            lastUpdate = datetime.datetime.now()             
            t = (lastUpdate - start).total_seconds()
            self.scene.UpdateAnimation(t)
            self.webCtrl.view_update()
            while (datetime.datetime.now()-lastUpdate).total_seconds() < 0.1:
                await asyncio.sleep(0.001)

        # 注销异步程序
        if self.animationFlag == False:
            print('线程退出')
            return